package Servlet;

import DAO.CustomerDAO;
import DAO.DAOFactory;

import javabean.Customer;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet ("/Login")
public class LoginServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        CustomerDAO customerDAO = (CustomerDAO) DAOFactory.getCustomerDAOInstance();
        String customerID = req.getParameter("username");
        String password = req.getParameter("password");
        String role = req.getParameter("role");
        System.out.println(role);
        HttpSession session = req.getSession();
        if(role.equals("Customer")) {
            Customer customer = new Customer();
            customer.setCustomerID(customerID);
            customer.setPassword(password);
            try {
                if (customerDAO.findLogin(customer)) {
                    Customer loginCustomer = customerDAO.SearchCustomer(customerID);
                    session.setAttribute("loginCustomer", loginCustomer);
                    resp.sendRedirect("Personal_Info.jsp");
                } else {
                    resp.sendRedirect("Login.jsp");
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
